/**
 * DataStorage.java
 *
 * Version:
 *     $Id$
 *
 * Revisions:
 *     $Log$
 */
package com.dietdroid;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import android.content.Context;
import android.util.Log;

/**
 *
 *
 * @author Alexander Zlatin
 *
 */
public class DataStorage {
    private static String profilePath = "MedProf.ser";
    private static ProfileData profileData = null;
    private static String historyPath = "History.ser";
    private static HistoryData historyData = null;
    
    public static ProfileData getProfileData(Context ctx) {
        if (profileData == null) {
            profileData = (ProfileData) load(profilePath, ctx);
        }
        if (profileData == null) {
            profileData = new ProfileData();
        }
        return profileData;
    }
    public static boolean saveProfileData(Context ctx, ProfileData data) {
        return save(profilePath, data, ctx);
    }
    
    public static HistoryData getHistoryData(Context ctx) {
        if (historyData == null) {
            historyData = (HistoryData) load(historyPath, ctx);
        }
        if (historyData == null) {
            historyData = new HistoryData();
        }
        return historyData;
    }
    public static boolean saveHistoryData(Context ctx, HistoryData data)  {
        return save(historyPath, data, ctx);
    }
    
    
    
    public static Object load(String filename, Context ctx) {
        Object retval = null;
        FileInputStream fis;
        try {
        	fis = ctx.openFileInput(filename); 
            ObjectInputStream in = new ObjectInputStream(fis);
            retval = in.readObject(); 
        } catch (Exception e) {
            Log.v("Load Error", e.getMessage());
        }
        return retval;
    }
    
    
    public static boolean save(String filename, Serializable data, Context ctx) {
        FileOutputStream fos = null;
        ObjectOutputStream out = null;
        try {
        	fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
            out = new ObjectOutputStream(fos);
            out.writeObject(data);
            out.close();
        } catch (IOException e) {
            Log.v("Save Error", e.toString());
            return false;
        }
        return true;
    }
}
